package org.alis.ap.rpc.transport.http;

import lombok.extern.slf4j.Slf4j;
import org.alis.ap.rpc.Peer;
import org.alis.ap.rpc.transport.TransportClient;
import org.alis.rpc.common.exception.NetWorkException;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * ApClient desc:
 *
 * @author luochuan
 * @date 2020/10/16 16:27
 */
@Slf4j
public class ApTransportClient implements TransportClient {
    private String url;

    @Override
    public void connect(Peer peer) {
        this.url = "http://" + peer.getHost() + ":" + peer.getPort();
    }

    @Override
    public InputStream write(InputStream inputStream) {
        try {
            URLConnection urlConnection = new URL(url).openConnection();
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);
            ((HttpURLConnection) urlConnection).setRequestMethod("POST");
            urlConnection.connect();
            IOUtils.copy(inputStream, urlConnection.getOutputStream());
            int resultCode = ((HttpURLConnection) urlConnection).getResponseCode();
            if (resultCode == HttpURLConnection.HTTP_OK) {
                return urlConnection.getInputStream();
            } else {
                return ((HttpURLConnection) urlConnection).getErrorStream();
            }
        } catch (Exception e) {
            throw new NetWorkException("network invoke error", e);
        }
    }

    /**
     * 后期池化后优化断开链接方法
     */
    @Override
    public void disconnect() {
        log.info("与服务器:{}的链接关闭", url);
    }
}
